package com.bingfor.easycablelink.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.databinding.ObservableInt;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.bingfor.easycablelink.R;
import com.bingfor.easycablelink.utils.ToastUtil;
import com.bingfor.easycablelink.widgets.OnRecyclerViewScrollListener;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nispok.snackbar.listeners.ActionClickListener;

import rx.Subscription;

/**
 * Created by Modificator
 * Date: 2016/2/17
 * Time: 17:41
 * Connect: yunshangcn@gmail.com
 */
public abstract class BaseRecyclerViewActivity extends BaseActivity {

    View internalEmpty = null;
    public SwipeRefreshLayout mSwipeRefresh = null;
    public RecyclerView mRecyclerView = null;
    public LinearLayout container = null;
    //标记当前页数，总页数
    protected int pageIndex = 1, pageCount = 1;
    Snackbar loadingSnackBar;
    public RecyclerView.LayoutManager mLayoutManager = null;
    int topPadding = 0;
    int bottomPadding = 0;

    /**
     * 1.正常显示
     * 2.加载中
     * 3.网络错误
     * 4.服务器错误
     * 5.无数据
     */
    protected ObservableInt pageStatus = new ObservableInt(2);
    protected int PAGE_STATUS_SHOW = 1;
    protected int PAGE_STATUS_LOADING = 2;
    protected int PAGE_STATUS_NETWORK_ERROR = 3;
    protected int PAGE_STATUS_SERVER_ERROR = 4;
    protected int PAGE_STATUS_DATA_EMPTY = 5;
    protected int PAGE_STATUS_OTHER_ERROR = 6;

    private OnRecyclerViewScrollListener recyclerViewScrollListener;
    Subscription dataLoadSubscription;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
        public void initViews() {
        internalEmpty = $(R.id.internalEmpty);
        mSwipeRefresh = $(R.id.mSwipeRefresh);
        mRecyclerView = $(R.id.mRecyclerView);
        container = $(R.id.container);
        //隐藏列表，显示加载页面
        internalEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reload();
            }
        });
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        mRecyclerView.addOnScrollListener(onScrollListener);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
       /* mRecyclerView.setItemAnimator(new BaseItemAnimator() {
            @Override
            protected void preAnimateAdd(RecyclerView.ViewHolder holder) {
                super.preAnimateAdd(holder);
                ViewCompat.setTranslationY(holder.itemView, holder.itemView.getMeasuredHeight() / 2f);
            }

            @Override
            public boolean animateAdd(RecyclerView.ViewHolder holder) {
                holder.itemView.animate().translationY(0);
                return super.animateAdd(holder);
            }

            @Override
            public boolean animateChange(RecyclerView.ViewHolder oldHolder, RecyclerView.ViewHolder newHolder, int fromX, int fromY, int toX, int toY) {
                return super.animateChange(oldHolder, newHolder, fromX, fromY, toX, toY);
            }
        });*/
    }

    public void loadSuccess() {
        pageStatus.set(1);
        mSwipeRefresh.setRefreshing(false);
        if (loadingSnackBar != null) {
            loadingSnackBar.dismiss();
            SnackbarManager.dismiss();
        }
    }

    public abstract void reload();


    public void connectFailed() {
        pageStatus.set(3);
        if (loadingSnackBar != null) {
            loadingSnackBar.dismiss();
            SnackbarManager.dismiss();
        }
    }

    public void loadError() {
        pageStatus.set(4);
        if (loadingSnackBar != null) {
            loadingSnackBar.dismiss();
            SnackbarManager.dismiss();
        }
    }

    public void setTopPadding(int topPadding) {
        this.topPadding = topPadding;
        mRecyclerView.setPadding(0, topPadding, 0, bottomPadding);
    }

    public void setBottomPadding(int bottomPadding) {
        this.bottomPadding = bottomPadding;
        mRecyclerView.setPadding(0, topPadding, 0, bottomPadding);
    }

    public void setRecyclerViewScrollListener(OnRecyclerViewScrollListener recyclerViewScrollListener) {
        this.recyclerViewScrollListener = recyclerViewScrollListener;
    }

    public void hideLoadingStatus() {
        if (loadingSnackBar != null) {
            loadingSnackBar.dismiss();
            SnackbarManager.dismiss();
        }
        mSwipeRefresh.setRefreshing(false);
    }

    //加载更多
    RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (recyclerViewScrollListener != null)
                recyclerViewScrollListener.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (recyclerViewScrollListener != null) {
                recyclerViewScrollListener.onScrolled(recyclerView, dx, dy);
            }
            int lastVisibleItem = 0;
            int totalOffset = 0;
            if (mLayoutManager instanceof LinearLayoutManager) {
                lastVisibleItem = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                totalOffset = 2;
            } else if (mLayoutManager instanceof GridLayoutManager) {
                lastVisibleItem = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                totalOffset = ((GridLayoutManager) mLayoutManager).getSpanCount() * 2;
            } else if (mLayoutManager instanceof StaggeredGridLayoutManager) {
                int[] visibleItems =
                        ((StaggeredGridLayoutManager) mLayoutManager).findLastVisibleItemPositions(null);
                for (int i = 0; i < visibleItems.length; i++) {
                    if (visibleItems[i] > lastVisibleItem)
                        lastVisibleItem = visibleItems[i];
                }
                totalOffset = ((StaggeredGridLayoutManager) mLayoutManager).getSpanCount() * 2;
            }
            int totalItemCount = mLayoutManager.getItemCount();
            if (pageIndex < pageCount && lastVisibleItem >= totalItemCount - totalOffset && !mSwipeRefresh.isRefreshing() && dataLoadSubscription != null && dataLoadSubscription.isUnsubscribed()) {// && (requestHandle == null || (requestHandle != null && requestHandle.isFinished()))) {
                pageIndex++;
                loadingSnackBar = Snackbar.with(mContext)
                        .text("正在加载更多...")
                        .actionLabel("取消")
                        .duration(Snackbar.SnackbarDuration.LENGTH_INDEFINITE)
                        .color(0xff434142).actionListener(new ActionClickListener() {
                            @Override
                            public void onActionClicked(Snackbar snackbar) {
                                //if (requestHandle != null)
//                                    requestHandle.cancel(true);
                            }
                        }).margin(0, 0, 0, bottomPadding)
                        .actionColor(getResources().getColor(android.R.color.white));
                mSwipeRefresh.setEnabled(false);
                refresh();
                SnackbarManager.show(loadingSnackBar, (ViewGroup) $(R.id.root));
            }
        }
    };


    public void showWaitDialog(String message) {
        if (waitDialog == null)
            waitDialog = new ProgressDialog(mContext);
        waitDialog.setCanceledOnTouchOutside(false);
        waitDialog.setMessage(message);
        if (!waitDialog.isShowing())
            waitDialog.show();
    }


    public void showWaitDialog() {
        showWaitDialog("正在加载...");
    }


    public void dismissWaitDialog() {
        waitDialog.dismiss();
    }

    long maxProgress = 100;
    ProgressDialog progressDialog;


    public void showProgressDialog(String title, String message, long maxProgress, long progress) {
        if (progressDialog == null || !progressDialog.isShowing()) {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        }
        if (title != null && title.length() > 0)
            progressDialog.setTitle(title);
        if (message != null && message.length() > 0)
            progressDialog.setMessage(message);
        progressDialog.setMax((int) (maxProgress == 0 ? progress > 100 ? progress : this.maxProgress : maxProgress));
        progressDialog.setProgress((int) progress);
        progressDialog.show();
    }


    public void showProgressDialog(String title, long maxProgerss, long progerss) {
        showProgressDialog(title, null, maxProgerss, progerss);
    }


    public void showProgressDialog(long maxProgerss, long progerss) {
        showProgressDialog(null, maxProgerss, progerss);
    }


    public void showProgressDialog(long progerss) {
        showProgressDialog(0, progerss);
    }


    public void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
    }

    public void showShortToast(String message) {
        ToastUtil.showToast(mContext, message);
    }


    public void showShortToast(@StringRes int resId) {
        showShortToast(getString(resId));
    }


    public void showLongToast(String message) {
        ToastUtil.showToast(mContext, message);
    }


    public void showLongToast(@StringRes int resId) {
        showLongToast(getString(resId));
    }


    /**
     * 获取是否有网络连接方法
     *
     * @param context
     * @return
     */
    public static NetworkInfo getActiveNetwork(Context context) {
        if (context == null)
            return null;
        ConnectivityManager mConnMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (mConnMgr == null)
            return null;
        NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo();
        // 获取活动网络连接信息
        return aActiveInfo;
    }

}
